package com.pokermind.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * JSON工具类 - 基于Jackson实现
 * 提供简洁易用的JSON序列化/反序列化功能
 * 
 * @author PokerMind Team
 */
public class JsonUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
    static {
        // 配置ObjectMapper
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }
    
    /**
     * 对象转JSON字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("Object to JSON failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 对象转格式化的JSON字符串（美化输出）
     */
    public static String toPrettyJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("Object to pretty JSON failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * JSON字符串转对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            logger.error("JSON to object failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * JSON字符串转复杂对象（支持泛型）
     */
    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            logger.error("JSON to generic object failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * JSON字符串转List
     */
    public static <T> List<T> fromJsonToList(String json, Class<T> elementClass) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, 
                OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, elementClass));
        } catch (JsonProcessingException e) {
            logger.error("JSON to List failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * JSON字符串转Map
     */
    public static Map<String, Object> fromJsonToMap(String json) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            logger.error("JSON to Map failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * JSON字符串转JsonNode（用于复杂JSON操作）
     */
    public static JsonNode parseToNode(String json) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readTree(json);
        } catch (JsonProcessingException e) {
            logger.error("JSON to JsonNode failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 判断字符串是否为有效JSON
     */
    public static boolean isValidJson(String json) {
        if (json == null || json.trim().isEmpty()) {
            return false;
        }
        try {
            OBJECT_MAPPER.readTree(json);
            return true;
        } catch (JsonProcessingException e) {
            return false;
        }
    }
    
    /**
     * 对象深拷贝（通过JSON序列化/反序列化）
     */
    public static <T> T deepCopy(T obj, Class<T> clazz) {
        if (obj == null) {
            return null;
        }
        try {
            String json = toJson(obj);
            return fromJson(json, clazz);
        } catch (Exception e) {
            logger.error("Deep copy failed: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 获取ObjectMapper实例（高级用法）
     */
    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }
    
    /**
     * 安全的JSON转换（带默认值）
     */
    public static <T> T fromJsonSafe(String json, Class<T> clazz, T defaultValue) {
        T result = fromJson(json, clazz);
        return result != null ? result : defaultValue;
    }
    
    /**
     * 从对象中提取JSON字段值
     */
    public static String getJsonFieldValue(Object obj, String fieldPath) {
        if (obj == null || fieldPath == null) {
            return null;
        }
        try {
            JsonNode node = OBJECT_MAPPER.valueToTree(obj);
            String[] paths = fieldPath.split("\\.");
            for (String path : paths) {
                if (node == null || !node.has(path)) {
                    return null;
                }
                node = node.get(path);
            }
            return node != null ? node.asText() : null;
        } catch (Exception e) {
            logger.error("Get JSON field value failed: {}", e.getMessage(), e);
            return null;
        }
    }
}
